package lpath

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// GetRootPath 获取程序根目录
func GetRootPath() (string, string) {
	proc, err := exec.LookPath(os.Args[0])
	if err != nil {
		panic(fmt.Sprintf("获取程序名失败。err: %v\n", err))
	}

	procPath, err := filepath.Abs(proc)
	if err != nil {
		panic(fmt.Sprintf("获取程序路径失败。err: %v\n", err))
	}

	pathSlice := strings.Split(procPath, "/")
	rootPath := strings.Join(pathSlice[:len(pathSlice)-1], "/")
	return rootPath, pathSlice[len(pathSlice)-1]
}

// MkdirAll 判断，并创建目录
func MkdirAll(path string) error {
	fi, err := os.Stat(path)
	if err == nil {
		if fi.IsDir() {
			return nil
		}
		if err := os.Remove(path); err != nil {
			return err
		}

	}
	if err := os.MkdirAll(path, 0755); err != nil {
		return err
	}
	return nil
}

// SetAbsPath 配置以程序工作目录为根的绝对路径
func SetAbsPath(path string) string {
	rootPath, _ := GetRootPath()
	if !strings.HasPrefix(path, "/") {
		path = rootPath + "/" + path
	}
	return path
}
